package com.cmpan.networkdisk.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * ClassName:LogAspect
 * Package:com.cmpan.networkdisk.aspect
 * Description:
 *
 * @Date:2020/7/6 16:53
 * @com.chuangmei
 */
@Aspect
@Component
public class LogAspect {

    //打印日志
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Pointcut("execution(* com.cmpan.networkdisk.controller.*.*(..))")
    public void log(){};

    @Before("log()")
    public void before(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //获取信息
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classM8ethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();

        //封装数据
        Information information = new Information(url,ip,classM8ethod,args);

        //打印日志
        logger.info("Request: {}",information);
    }

    //After
    @After("log()")
    public void after(){
        logger.info("---------After---------");
    }

    //AfterReurning
    @AfterReturning(returning = "result" , pointcut = "log()")
    public void afterreturning(Object result){
        logger.info("result: {}",result);
    }

    //class
    private class Information{

        //Filed
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        //constructor
        public Information(String url, String ip, String classMethod, Object[] args) {
            this.url = url;
            this.ip = ip;
            this.classMethod = classMethod;
            this.args = args;
        }

        @Override
        public String toString() {
            return "Information{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
